<template>
  <div>
    <div style="padding-left:12px;padding-right:12px" @click="clickIcon">
      <el-badge :value="unreadCount" :max="99" :hidden="(unreadCount || 0) == 0">
        <svg-icon class="svg" icon-class="message-center"/>
      </el-badge>
    </div>
    <el-drawer title="消息中心" :visible.sync="drawVisible" direction="rtl" size="30%" append-to-body destroy-on-close
               :modal="false" @open="openDrawer" @close="closeDrawer"
    >
      <div class="margin-lr flex justify-end align-center flex-no-wrap">
        <el-button type="primary" plain size="mini" @click="readAll">全部已读</el-button>
      </div>
      <el-table ref="messageTable" :row-class-name="tableRowClassName" :data="tableData" tooltip-effect="dark"
                v-loading="tabLoading" size="mini" class="el-table" highlight-current-row stripe style="width: 100%"
                :max-height="tableMaxHeight" @row-click="clickRow" row-key="id"
      >
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div class="margin-lr margin-tb-xs">
              <p class="text-xs" v-html="scope.row.content" style="line-height: 18px;margin:0"></p>
              <div v-if="!!scope.row.to_router_name" class="flex justify-start align-center flex-no-wrap">
                <el-button type="text" size="mini" @click="toHandle(scope.row)">前往处理</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="60">
          <template slot-scope="scope">
            <div class="flex justify-start align-center flex-no-wrap">
              <el-tag v-if="scope.row.type==1" type="primary" size="mini" effect="plain">系统</el-tag>
              <el-tag v-if="scope.row.type==2" type="success" size="mini" effect="plain">审批</el-tag>
              <el-tag v-if="scope.row.type==3" type="success" size="mini" effect="plain">抄送</el-tag>
              <el-tag v-if="scope.row.type==4" type="warning" size="mini" effect="plain">任务</el-tag>
              <el-tag v-if="scope.row.type==5" type="warning" size="mini" effect="plain">提醒</el-tag>
              <el-tag v-if="scope.row.type==6" type="danger" size="mini" effect="plain">推送</el-tag>
              <el-tag v-if="scope.row.type==7" type="info" size="mini" effect="plain">其他</el-tag>
              <el-badge is-dot v-if="!scope.row.read_at"/>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="created_at" label="时间" width="135"></el-table-column>
        <el-table-column property="title" label="消息标题"></el-table-column>
      </el-table>
      <div class="flex justify-end align-center flex-no-wrap">
        <el-pagination small :current-page.sync="current" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :page-sizes="[10, 20, 50, 100]" :page-size="listParams.page_size"
                       layout="total, sizes, prev, pager, next" :total="total"
        ></el-pagination>
      </div>

    </el-drawer>
  </div>
</template>

<script>
import { get_own_unread_count, list, set_has_read } from '@/api/system/message_center.js'
import handleUtil from '@/views/personal/handle/js/handle.js'
import distinct_arr from '@/views/personal/handle/js/routerUtil'
import { generateUUID } from '@/utils/util'
import { outputDir } from '@/settings'

export default {
  name: 'MessageCenterIcon',
  beforeDestroy() {
    clearInterval(this.timer)
  },
  // beforeRouteLeave(to, from, next) {
  //   this.$destroy()
  //   next()
  // },
  props: {},
  data() {
    return {
      timer: null,
      unreadCount: 0,
      tabLoading: false,
      listParams: {
        page: 1,
        page_size: 10
      }, // list参数
      current: 1,
      total: 0,

      drawVisible: false,
      tableData: []
    }
  },
  watch: {},
  computed: {
    tableMaxHeight() {
      return document.documentElement.clientHeight - 150
    }
  },
  created() {

  },
  mounted() {
    this.getUnreadCount()
    if('local' !== outputDir) this.timer = setInterval(this.getUnreadCount, 5000)
  },
  methods: {
    toHandle(row) {
      const that = this
      const toHandle = (data) => {
        if (!!data.to_router_path) {
          let obj = {
            path: data.to_router_path
          }
          if (!!data.to_router_querys && data.to_router_querys !== '{}') {
            obj.query = JSON.parse(data.to_router_querys)
          }
          that.$router.push(obj)
        } else if (!!data.to_router_name) {
          let obj = {
            name: data.to_router_name
          }
          if (!!data.to_router_params && data.to_router_params !== '{}') {
            obj.params = JSON.parse(data.to_router_params)
          }
          that.$router.push(obj)
        }
      }

      if (row.type == 1) { // 系统
        toHandle(row)
      }
      if (row.type == 2) { // 审批
        if (row.flow_status == 1) { // 待审批
          // that.$router.push({
          // 	name: that.$store.getters.getFlowTypeRouter(row.flow_type),
          // 	params: handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 2, 1, row.flow_type)
          // })
          const tmp_arr = distinct_arr
          let flowTypeRouter = that.$store.getters.getFlowTypeRouter(row.flow_type)
          let params = handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 2, 1, row.flow_type)
          if (tmp_arr.includes(flowTypeRouter)) {
            const uuid = generateUUID()
            this.$store.commit('keep/PUT_PAGE_PARAMS', {
              uuid: uuid,
              data: params
            })
            this.$router.push({
              name: flowTypeRouter,
              query: {
                uuid: uuid
              }
            })
          } else {
            that.$router.push({
              name: that.$store.getters.getFlowTypeRouter(row.flow_type),
              params: params
            })
          }
        }
        if (row.flow_status == 2) { // 已通过
          // that.$router.push({
          // 	name: that.$store.getters.getFlowTypeRouter(row.flow_type),
          // 	params: handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 3, 2, row.flow_type)
          // })
          const tmp_arr = distinct_arr
          let flowTypeRouter = that.$store.getters.getFlowTypeRouter(row.flow_type)
          let params = handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 3, 2, row.flow_type)
          if (tmp_arr.includes(flowTypeRouter)) {
            const uuid = generateUUID()
            this.$store.commit('keep/PUT_PAGE_PARAMS', {
              uuid: uuid,
              data: params
            })
            this.$router.push({
              name: flowTypeRouter,
              query: {
                uuid: uuid
              }
            })
          } else {
            that.$router.push({
              name: that.$store.getters.getFlowTypeRouter(row.flow_type),
              params: params
            })
          }
        }
        if (row.flow_status == 3) { // 被退回
          // that.$router.push({
          // 	name: that.$store.getters.getFlowTypeRouter(row.flow_type),
          // 	params: handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 1, 4, row.flow_type)
          // })
          const tmp_arr = distinct_arr
          let flowTypeRouter = that.$store.getters.getFlowTypeRouter(row.flow_type)
          let params = handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 1, 4, row.flow_type)
          if (tmp_arr.includes(flowTypeRouter)) {
            const uuid = generateUUID()
            this.$store.commit('keep/PUT_PAGE_PARAMS', {
              uuid: uuid,
              data: params
            })
            this.$router.push({
              name: flowTypeRouter,
              query: {
                uuid: uuid
              }
            })
          } else {
            that.$router.push({
              name: that.$store.getters.getFlowTypeRouter(row.flow_type),
              params: params
            })
          }
        }
      }
      if (row.type == 3) { // 抄送
        const tmp_arr = distinct_arr
        let flowTypeRouter = that.$store.getters.getFlowTypeRouter(row.flow_type)
        let params = handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 3, 7, row.flow_type)
        if (tmp_arr.includes(flowTypeRouter)) {
          const uuid = generateUUID()
          this.$store.commit('keep/PUT_PAGE_PARAMS', {
            uuid: uuid,
            data: params
          })
          this.$router.push({
            name: flowTypeRouter,
            query: {
              uuid: uuid
            }
          })
        } else {
          that.$router.push({
            name: that.$store.getters.getFlowTypeRouter(row.flow_type),
            params: params
          })
        }
        // that.$router.push({
        // 	name: that.$store.getters.getFlowTypeRouter(row.flow_type),
        // 	params: handleUtil.genRedirectParam(row.wf_data_id, row.data_id, 3, 7, row.flow_type)
        // })
      }
      if (row.type == 4) { // 任务
        toHandle(row)
      }
      if (row.type == 5) { // 提醒
        toHandle(row)
      }
      if (row.type == 6) { // 推送
        toHandle(row)
      }
      if (row.type == 7) { // 其他
        toHandle(row)
      }
    },
    getUnreadCount() {
      return get_own_unread_count()
      	.then(res => {
      		let {
      			data
      		} = res
      		this.unreadCount = data || 0;
      	})
      	.catch(() => {
      	})
    },
    openDrawer() {
      this.getList()
    },
    closeDrawer() {
      this.listParams = {
        page: 1,
        page_size: 10
      }
      this.current = 1
      this.total = 0
    },
    clickIcon() {
      this.drawVisible = true
    },
    getList() {
      this.tabLoading = true
      return list(this.listParams)
        .then(res => {
          let {
            data: {
              records,
              total
            }
          } = res
          this.tableData = records
          this.total = total
          this.tabLoading = false
        })
        .catch(() => {
          this.tabLoading = false
        })
    },
    readAll() {
      // 设置表格中当前页消息全部已读
      this.tabLoading = true
      return set_has_read({
        ids: this.tableData.map(d => (d.id))
      })
        .then(res => {
          this.getList()
          this.tabLoading = false
        })
        .catch(() => {
          this.tabLoading = false
        })
    },
    setHasRead(row) {
      // console.log(row);
      if (!row.read_at) {
        this.$set(this.tableData, row.index, Object.assign({}, row, {
          read_at: 1
        }))
        // 静默请求，设置消息已读
        set_has_read({
          ids: [row.id]
        })
      }
    },
    clickRow(row, col, e) {
      this.$refs.messageTable.toggleRowExpansion(row)
      this.setHasRead(row)
    },
    // 分页 -pageSize改变
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    // 分页 当前页面改变
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    //带状态表格
    tableRowClassName({
      row,
      rowIndex
    }) {
      row.index = rowIndex
      return 'active-row'
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/table-scrollbar.scss';

.svg {
  display: table-cell;
  cursor: pointer;
  fill: #5a5e66;
  width: 20px;
  height: 20px;
  vertical-align: 10px;
}

/deep/ .el-table {
  .active-row:hover {
    cursor: pointer;
    color: #409EFF;
    text-shadow: 0 0 1px #c6eeff;
    //text-decoration: underline;
  }

  .el-table__body,
  .el-table__header {
    width: 565px !important;
  }
}
</style>
